package m.jclecai.com.activity.follow;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.adapter.CommonPagerAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.Response.ResHotPeopleInfo;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.fragment.follow.GenDanHongRenDetailFragment;
import m.jclecai.com.inter.OnCautionDialogConfirmListener;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.CautionDialog;
import m.jclecai.com.view.frag_vp_frag.ObservableScrollView;
import m.jclecai.com.view.frag_vp_frag.PersonalViewpager;

/**
 * 这里是个人购买的记录介绍
 */
public class HotPeopleInfoActivity extends BaseActivity {


    @BindView(R.id.iv_user_icon)
    ImageView mIvUserIcon;


    @BindView(R.id.iv_user_rank)
    ImageView mIvUserRank;

    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.tv_fans)
    TextView mTvFans;
    @BindView(R.id.tv_win_total_money)
    TextView mTvWinTotalMoney;
    @BindView(R.id.tv_unit_award)
    TextView mTvUnitAward;
    @BindView(R.id.tv_seven_day_award)
    TextView mTvSevenDayAward;
    @BindView(R.id.tv_thirty_day_award)
    TextView mTvThirtyDayAward;
    @BindView(R.id.tv_value)
    TextView mTvValue;

    @BindViews({R.id.iv_term_one,
            R.id.iv_term_two,
            R.id.iv_term_three,
            R.id.iv_term_four,
            R.id.iv_term_five,})
    ImageView[] mIvTermImgs;
    //关注
    @BindView(R.id.ll_follow)
    LinearLayout mLlFollow;

    @BindView(R.id.tv_follow_statue)
    TextView mTvFollowStatue;

    @BindView(R.id.tv_custom_order)
    TextView mTvCustomOrder;

    //定制跟单；
    @BindView(R.id.ll_custom_follow)
    LinearLayout mLlCustomFollow;

    @BindView(R.id.scrollView_main)
    public ObservableScrollView scrollView_main;

    public static final String HOT_PEOPLE_ID = "userId";
    @BindView(R.id.vp_gendan_hot_people_detail)
    PersonalViewpager vp_gendan_hot_people_detail;
    @BindView(R.id.tl_gendan_hot_people_detail)
    TabLayout tl_gendan_hot_people_detail;

    @BindView(R.id.tl_gendan_hot_people_detail2)
    TabLayout tl_gendan_hot_people_detail2;

    @BindView(R.id.rl_bar)
    RelativeLayout rl_bar;

    @BindView(R.id.tv_hotpeople_daihong)
    TextView tv_hotpeople_daihong;

    @BindView(R.id.tv_hotpeople_yingli)
    TextView tv_hotpeople_yingli;

    @BindView(R.id.tv_guanzhu)
    TextView tv_guanzhu;
    //    private PullToRefreshListView mRefreshListView;
//    private ListView mListView;
//    private HotPeopleInfoAdapter mHotPeopleInfoAdapter;
    private ResHotPeopleInfo mResHotPeopleInfo;
    private String mHotPeopleId;
    ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private int statusBarHeight;
    private int topLayoutHeight;
    private int maxDiff = 0;

    @Override
    protected int getContentView() {
        return R.layout.activity_hot_people_info;
    }

    @Override
    protected void initLoadingView() {
        super.initLoadingView();
//        mRefreshListView = (PullToRefreshListView) findViewById(R.id.prl_list_view);
//        mListView = mRefreshListView.getRefreshableView();
//        mListView.addHeaderView(View.inflate(this, R.layout.header_hot_people_info, null));
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("红人详情");
        leftOptionText("");
    }

    @Override
    protected void initData() {
        super.initData();
        mHotPeopleId = getIntent().getStringExtra(HOT_PEOPLE_ID);
        statusBarHeight = ScreenUtil.getStatusBarHeight(getApplicationContext());
        topLayoutHeight = ScreenUtil.getMeasureHeight(rl_bar);
        initFragment();
//        mHotPeopleInfoAdapter = new HotPeopleInfoAdapter();
//        mRefreshListView.setAdapter(mHotPeopleInfoAdapter);


        requestData(mHotPeopleId);

    }


    private void initFragment() {
        fragmentArrayList.add(GenDanHongRenDetailFragment.newInstance(0, mHotPeopleId));
        fragmentArrayList.add(GenDanHongRenDetailFragment.newInstance(5, mHotPeopleId));
        fragmentArrayList.add(GenDanHongRenDetailFragment.newInstance(6, mHotPeopleId));
        fragmentArrayList.add(GenDanHongRenDetailFragment.newInstance(99, mHotPeopleId));
        vp_gendan_hot_people_detail.setAdapter(new CommonPagerAdapter(this, fragmentArrayList, R.array.touzhu_record_title, getSupportFragmentManager()));
        vp_gendan_hot_people_detail.setOffscreenPageLimit(5);
        tl_gendan_hot_people_detail.setupWithViewPager(vp_gendan_hot_people_detail);
        tl_gendan_hot_people_detail2.setupWithViewPager(vp_gendan_hot_people_detail);
        vp_gendan_hot_people_detail.setCurrentItem(getIntent().getIntExtra("order_position", 0), false);
        initScrollViewListener();
    }

    private void initScrollViewListener() {
        scrollView_main.setScrollViewListener(new ObservableScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(NestedScrollView scrollView, int x, int y, int oldx, int oldy) {
                //悬停tab
                int[] location = new int[2];
                tl_gendan_hot_people_detail.getLocationOnScreen(location);
                int yPosition = location[1];
                int visibleY = statusBarHeight + topLayoutHeight;
                Log.v("params", statusBarHeight + ">>" + topLayoutHeight + "  yPosition" + yPosition);

                if (yPosition <= visibleY) {
                    tl_gendan_hot_people_detail.setVisibility(View.INVISIBLE);
                    tl_gendan_hot_people_detail2.setVisibility(View.VISIBLE);
                } else {
                    tl_gendan_hot_people_detail2.setVisibility(View.GONE);
                    tl_gendan_hot_people_detail.setVisibility(View.VISIBLE);
                }
                if (yPosition - visibleY > maxDiff) {//获取最大间距
                    maxDiff = yPosition - visibleY;
                }
//            PluLog.i("LHD PersonalCenterActivity    y = $yPosition   maxDiff = $maxDiff")
                //tab 渐变
                if (maxDiff <= 0) return;
                int diff = yPosition - visibleY;
                DecimalFormat df = new DecimalFormat("0.0");
//            PluLog.i("LHD  距离 = $diff  maxDiff = $maxDiff" + "   比例 = " + df.format(diff * 255 / maxDiff) + "  最终值 = " + df.format(diff * 255 / maxDiff))
                if (diff >= 0) {
                    String valueLong = df.format(diff * 255 / maxDiff);
                    String value = valueLong.substring(0, valueLong.length() - 2);
//                PluLog.i("LHD 最终透明值 ： $value")
                    int alph = 255 - Integer.parseInt(value);
//                PluLog.i("LHD  透明值 = $alph    $value")
//                    relaTop.setBackgroundColor(Color.argb(alph, 47, 48, 47));
                } else {
//                    relaTop.setBackgroundColor(Color.argb(255, 47, 48, 47));
                }

                //上拉加载
                if (y == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
                    Log.i("LHD", "LHHD >>>>>>>>>>>>>  滑动到底部");
//                    ((GenDanHongRenDetailFragment)fragmentArrayList.get(vp_gendan_hot_people_detail.getCurrentItem())).loadMore();
//                    fragmentOne.loadMore();
                }
            }
        });
    }

    public void requestData(String hotPeopleId) {
        requestHeader(hotPeopleId);
//        requestHotOrder(hotPeopleId);
    }

//    private void requestHotOrder(String hotPeopleId) {
//        //这里我们要请求的是热门的跟单；
//        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("id", mHotPeopleId);
//        showDialog();
//        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_ORDER, new HttpManager.StringCallback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//                DisPlay("网络异常!");
//                dissDialog();
//
//            }
//
//            @Override
//            public void onResponse(String response) {
//
//                try {
//                    if (!TextUtils.isEmpty(response)) {
//
//                        mResHotPeopleInfo = FastOk.get(response, ResHotPeopleInfo.class);
//                        if (mResHotPeopleInfo != null) {
//
//                            if ("0".equals(mResHotPeopleInfo.getStatus())) {
//
//                                mHotPeopleInfoAdapter.refresh(mResHotPeopleInfo.getRecords());
//                            } else {
//                                DisPlay(mResHotPeopleInfo.getMessage());
//                            }
//
//                        } else {
//                            DisPlay("网络异常!");
//                        }
//                    } else {
//                        DisPlay("网络异常!");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    DisPlay("网络异常!");
//                }
//            }
//        }, paramsMap);
//
//    }

    private void requestHeader(String hotPeopleId) {

        showDialog();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", hotPeopleId);
        paramsMap.put("user", PreferenceUtil.getUserName(this));
        HttpManager.postAsyn(Constant_Url.HOT_PEOPLE_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常!");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    mResHotPeopleInfo = FastOk.get(response, ResHotPeopleInfo.class);
                    if (mResHotPeopleInfo != null) {

                        if ("0".equals(mResHotPeopleInfo.getStatus())) {

                            updateHeader();
                            // mHotPeopleInfoAdapter.refresh(mResHotPeopleInfo.getRecords());
                        } else {
                            DisPlay(mResHotPeopleInfo.getMessage());
                        }

                    } else {
                        DisPlay("网络异常!");
                    }
                } else {
                    DisPlay("网络异常!");
                }
            }
        }, paramsMap);

    }

    /**
     * 这里我们是用来刷新头部的数据的
     */
    private void updateHeader() {
        //头部
        mTvFans.setText(Html.fromHtml("粉丝:<font color='red'>" + mResHotPeopleInfo.getFans() + "</font>"));
        tv_guanzhu.setText(Html.fromHtml("关注:<font color='red'>" + mResHotPeopleInfo.getAttention() + "</font>"));
        tv_hotpeople_daihong.setText(mResHotPeopleInfo.getWin_follows + "人");
        tv_hotpeople_yingli.setText(mResHotPeopleInfo.getPayback());
        mTvWinTotalMoney.setText("总共中奖:" + mResHotPeopleInfo.getWinmoneys_total());
        mTvNickname.setText(mResHotPeopleInfo.getUsername());
        Glide.with(this).load(mResHotPeopleInfo.getUser_face()).into(mIvUserIcon);

        if (mResHotPeopleInfo.getUser_rank() > 0) {
            mIvUserRank.setVisibility(View.VISIBLE);
        } else {
            mIvUserRank.setVisibility(View.INVISIBLE);
        }

        //中间的那一行
        mTvUnitAward.setText(mResHotPeopleInfo.getPayback_total());
        try {

            mTvSevenDayAward.setText(mResHotPeopleInfo.getMilitary().split("/")[0] + "中" + mResHotPeopleInfo.getMilitary().split("/")[1]);
        } catch (Exception e) {

        }
        mTvThirtyDayAward.setText(mResHotPeopleInfo.getMilitary_total());
        mTvValue.setText(mResHotPeopleInfo.getAll_winmoneys_total());
        //近5期的状况；
        for (int i = 0; i < mIvTermImgs.length; i++) {
            if (i < mResHotPeopleInfo.getWinstr().size()) {
                if (mResHotPeopleInfo.getWinstr().get(i).equals("0")) {
                    mIvTermImgs[i].setImageResource(R.drawable.follow_status5_nowin);
                } else {
                    mIvTermImgs[i].setImageResource(R.drawable.follow_status5_win);
                }
            } else {
                mIvTermImgs[i].setVisibility(View.INVISIBLE);
            }

        }
        //判断是否已经关注或者已经定制跟单了
        if ("1".equals(mResHotPeopleInfo.getAttention())) {
            mTvFollowStatue.setText("已关注");
        } else {
            mTvFollowStatue.setText("关注");
        }

        if ("1".equals(mResHotPeopleInfo.getFollowid())) {

            mTvCustomOrder.setText("已定制");

        } else {
            mTvCustomOrder.setText("定制跟单");
        }

    }


    //关注
    @OnClick(R.id.ll_follow)
    public void onClickFollow(View view) {

        showDialog();
        checkLogin(new Callback() {

            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                doFollowRequest();
            }

            @Override
            public void callbackField() {
                super.callbackField();
                dissDialog();
            }
        });
    }

    private void doFollowRequest() {
        final HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user", PreferenceUtil.getUserName(this));
        paramsMap.put("password", PreferenceUtil.getPassword(this));
        paramsMap.put("type", mTvFollowStatue.getText().equals("已关注") ? "del" : "add");
        paramsMap.put("id", mHotPeopleId);

        HttpManager.postAsyn(Constant_Url.FOLLOW_HOT_PEOPLE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if ("0".equals(proofBean.getStatus())) {
                        DisPlay(proofBean.getMessage());
                        String followStatue = mTvFollowStatue.getText().toString().equals("关注") ? "已关注" : "关注";
                        mTvFollowStatue.setText(followStatue);
                    } else {
                        DisPlay(proofBean.getMessage());
                    }
                } else {
                    DisPlay("网络异常!!!");
                }
            }
        }, paramsMap);
    }

    //定制跟单
    @OnClick(R.id.ll_custom_follow)
    public void onClickCustomFollow(View view) {
        String s = mTvCustomOrder.getText().toString();
        if ("已定制".equals(s)) {
            //这里我们要先取消才能定制；这里我们弹出一个对话框；
            CautionDialog CautionDialog = new CautionDialog(this, "取消定制？", new OnCautionDialogConfirmListener() {
                @Override
                public void onCancelListener() {
                }

                @Override
                public void onConfirmListener() {
                    //取消定制；
                    requestCustomCancelOrder();
                }
            });
            CautionDialog.show();
        } else {
            startActivity(CustomFollowOrderActivity.getIntent(this, mHotPeopleId));
        }
    }

    /**
     * 这里是需要登陆的；
     * 取消定制状态
     */
    private void requestCustomCancelOrder() {

        final HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user", PreferenceUtil.getUserName(this));
        paramsMap.put("password", PreferenceUtil.getPassword(this));
        paramsMap.put("id", mHotPeopleId);

        showDialog();
        HttpManager.postAsyn(Constant_Url.CANCEL_HOT_PEOPLE_OREDER, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("网络异常!!!");
            }

            @Override
            public void onResponse(String response) {
                //这里我们要做一个操作就是判断是否取消成
                if (!TextUtils.isEmpty(response)) {

                    ProofBean proofBean = FastOk.get(response, ProofBean.class);
                    if (proofBean != null && proofBean.getStatus().equals("0")) {
                        DisPlay("取消成功!!!");
                        mTvCustomOrder.setText("定制跟单");
                    } else {
                        if (proofBean != null) {
                            DisPlay(proofBean.getMessage());
                        } else {
                            DisPlay("网络异常！！！");
                        }
                    }

                } else {
                    DisPlay("网络异常!!!");
                }
                dissDialog();
            }
        }, paramsMap);

    }

    public static Intent getIntent(Context context, String hotPeopleId) {
        Intent intent = new Intent(context, HotPeopleInfoActivity.class);

        intent.putExtra(HOT_PEOPLE_ID, hotPeopleId);

        return intent;
    }
}
